﻿using System;
using UnityEngine;

namespace Common
{
    public static class Timer
    {
        private static double _gameStartTimeStamp;
        private static double _gameStartTime;
        private static double _time;
        // private static int _lastCalcFrame = -1;

        public static double CurrentTime
        {
            get
            {
                // if (_lastCalcFrame < Time.frameCount)  
                // {
                //     _lastCalcFrame = Time.frameCount;
                //     _time = DateTimeOffset.Now.ToUnixTimeSeconds();
                // }
                UpdateTime();
                return _time;
            }
        }

        public static void Init()
        {
            _gameStartTime = Time.realtimeSinceStartupAsDouble;
            _gameStartTimeStamp = DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000.0;
        }
        
        private static void UpdateTime()
        {
            _time = _gameStartTimeStamp + Time.realtimeSinceStartupAsDouble - _gameStartTime;
            // Debug.Log("_time: " + _time + " utc: " + DateTimeOffset.UtcNow.ToUnixTimeSeconds());
        }


        #region Time to String

        public static string Timer2String()
        {
            DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds((long)CurrentTime);
            // Debug.Log("_time: " + _time + " dateTimeOffset: " + new DateTimeOffset(dateTimeOffset.LocalDateTime).ToUnixTimeSeconds());
            return dateTimeOffset.LocalDateTime.ToString("yyyy-MM-dd HH:mm:ss");
        }

        #endregion
    }
}